'''
Virtual XML DOM support  

Created on Sep 28, 2010

@author: morgan
'''
# from string import Template
import xml.dom.minidom as xml

def _writexml(self, writer, indent="", addindent="", newl=""):
    """
    Fixes xml.dom.minidom's horrible whitespace problem. 
    Routine courtesy of Ron Rothman - http://ronrothman.com/  
    
    @indent = current indentation
    @addindent = indentation to add to higher levels
    @newl = newline string
    """
    writer.write(indent+"<" + self.tagName)

    attrs = self._get_attributes()
    a_names = attrs.keys()
    a_names.sort()

    for a_name in a_names:
        writer.write(" %s=\"" % a_name)
        xml._write_data(writer, attrs[a_name].value)
        writer.write("\"")
    if self.childNodes:
        if len(self.childNodes) == 1 \
          and self.childNodes[0].nodeType == xml.Node.TEXT_NODE:
            writer.write(">")
            self.childNodes[0].writexml(writer, "", "", "")
            writer.write("</%s>%s" % (self.tagName, newl))
            return
        writer.write(">%s"%(newl))
        for node in self.childNodes:
            node.writexml(writer,indent+addindent,addindent,newl)
        writer.write("%s</%s>%s" % (indent,self.tagName,newl))
    else:
        writer.write("/>%s"%(newl))
# replace minidom's function with ours
xml.Element.writexml = _writexml

#T=Template

def createElement(doc, tag, data):
    if type(data) == str:
        return __createTxtElement__(doc, tag, data)
    elif type(data) in [int, float]:
        return __createTxtElement__(doc, tag, str(data))
    elif type(data) == bool:
        return __createBoolElement__(doc, tag, data)
    elif data == None:
        return __createTxtElement__(doc, tag, "")
    
def createComment(doc, text):
    return doc.createComment(text)
    
def __createTxtElement__(doc, tag, text):
    special_chars = ['<', '>', '&', "'", '"', '\n', '\t']
    for c in special_chars:
        if text.find(c) != -1:
            return __createCDATAElement__(doc, tag, text)
    txtNode = doc.createTextNode(text)
    elem = doc.createElement(tag)
    elem.appendChild(txtNode)
    return elem

def __createBoolElement__(doc, tag, bool):
    if bool: 
        text = "1"
    else:
        text = "0"
    txtNode = doc.createTextNode(text)
    elem = doc.createElement(tag)
    elem.appendChild(txtNode)
    return elem

def __createCDATAElement__(doc, tag, text):
    CDATANode = doc.createCDATASection(text)
    elem = doc.createElement(tag)
    elem.appendChild(CDATANode)
    return elem
    
def createEmptyElement(doc, tag):
    return doc.createElement(tag)